package com.pinyougou.sellergoods.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.ISelect;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.pinyougou.common.PageResult;
import com.pinyougou.mapper.*;
import com.pinyougou.pojo.*;
import com.pinyougou.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class GoodsServiceImpl implements GoodsService
{
    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private GoodsDescMapper goodsDescMapper;
    @Autowired
    private ItemMapper itemMapper;

    @Autowired
    private ItemCatMapper itemCatMapper;
    @Autowired
    private BrandMapper brandMapper;
    @Autowired
    private SellerMapper sellerMapper;

    /**
     * 添加方法
     *
     * @param goods
     */
    @Override
    public void save(Goods goods)
    {
        // 1. 往tb_goods 插入记录
        goods.setAuditStatus("0");
        goodsMapper.insertSelective(goods);
        // 2. 往tb_goods_desc 插入记录
        goods.getGoodsDesc().setGoodsId(goods.getId());
        goodsDescMapper.insertSelective(goods.getGoodsDesc());
        // 3. 往tb_item 插入记录
            // 3.1 是否启用规格
        if("1".equals(goods.getIsEnableSpec()))
        {
            for(Item item : goods.getItemList())
            {
                //添加标题
                StringBuilder title = new StringBuilder(goods.getGoodsName());

                Map<String,String> specList = JSON.parseObject(item.getSpec(), Map.class);

                for (String spec : specList.values())
                {
                    //添加规格选项到 标题
                    title.append(" "+spec);
                }
                item.setTitle(title.toString());
                //设置商品的通用信息
                setItemInfo(goods,item);

                itemMapper.insertSelective(item);
            }
        }
        else
        {
            Item item = new Item();
            //设置商品的名称
            item.setTitle(goods.getGoodsName());
            //设置商品的价格
            item.setPrice(goods.getPrice());
            //设置商品的库存数量
            item.setNum(9999);
            //设置启用
            item.setStatus("1");
            //设置是否默认
            item.setIsDefault("1");
            //设置规格选项,用{}防止遍历的时候报错
            item.setSpec("{}");
            //设置商品的通用的信息
            setItemInfo(goods,item);

            itemMapper.insertSelective(item);
        }
    }

    /*设置商品的信息*/
    private void setItemInfo(Goods goods,Item item)
    {
        //添加商品的照片
        List<Map> imgList = JSON.parseArray(goods.getGoodsDesc().getItemImages(), Map.class);

        if (imgList != null && imgList.size()>0)
        {
            item.setImage(imgList.get(0).get("url").toString());
        }

        //SKU的目录都是末端目录也叫叶子目录
        item.setCategoryId(goods.getCategory3Id());
        item.setCreateTime(new Date());
        item.setUpdateTime(new Date());

        //设置 商品的编号
        item.setGoodsId(goods.getId());
        //设置商家编号
        item.setSellerId(goods.getSellerId());
        //设置商品分类名称
        ItemCat itemCat = itemCatMapper.selectByPrimaryKey(goods.getCategory3Id());
        item.setCategory(itemCat != null?itemCat.getName() : "");
        //设置品牌名称
        Brand brand = brandMapper.selectByPrimaryKey(goods.getBrandId());
        item.setBrand(brand !=null ? brand.getName() : "");
        //设置商家店铺名称
        Seller seller = sellerMapper.selectByPrimaryKey(goods.getSellerId());
        item.setSeller(seller != null ? seller.getNickName() : "");
    }

    /**
     * 修改方法
     *
     * @param goods
     */
    @Override
    public void update(Goods goods)
    {

    }

    /**
     * 根据主键id删除
     *
     * @param id
     */
    @Override
    public void delete(Serializable id)
    {

    }

    /**
     * 批量删除
     *
     * @param ids
     */
    @Override
    public void deleteAll(Serializable[] ids)
    {

    }

    /**
     * 根据主键id查询
     *
     * @param id
     */
    @Override
    public Goods findOne(Serializable id)
    {
        return null;
    }

    /**
     * 查询全部
     */
    @Override
    public List<Goods> findAll()
    {
        return null;
    }

    /**
     * 多条件分页查询
     *
     * @param goods
     * @param page
     * @param rows
     */
    @Override
    public PageResult findByPage(Goods goods, int page, int rows)
    {
        /*
        String sellerId = SecurityUtils.getSubject().getPrincipal().toString();
        goods.setSellerId(sellerId);
        */
        PageInfo<Map<String,Object>> pageInfo = PageHelper.startPage(page, rows).doSelectPageInfo(new ISelect()
        {
            @Override
            public void doSelect()
            {
                goodsMapper.findAll(goods);
            }
        });
        List<Map<String, Object>> goodsList = pageInfo.getList();
        for (Map<String, Object> map : goodsList)
        {
            Long category3Id = (Long) map.get("category3Id");
            if (category3Id != null)
            {
                //将goods中的categoryId 转换为对应的 Name
                ItemCat itemCat1 = itemCatMapper.selectByPrimaryKey(((Long) map.get("category1Id")));
                ItemCat itemCat2 = itemCatMapper.selectByPrimaryKey(((Long) map.get("category2Id")));
                ItemCat itemCat3 = itemCatMapper.selectByPrimaryKey((category3Id));

                map.put("category1Name",itemCat1.getName());
                map.put("category2Name",itemCat2.getName());
                map.put("category3Name",itemCat3.getName());
            }
        }

        return new PageResult(pageInfo.getPages(),goodsList);
    }

    /**批量修改商品状态*/
    public boolean updateStatus(String column, Long[] ids, String auditStatus)
    {
        try
        {
            goodsMapper.updateStatus(column,ids,auditStatus);
            return true;
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return false;
    }
}